package exttable.login;

import dbutils.DbUtils;
import exttable.SGTTestParametrs;
import exttable.formgenerator.StaticMethods;
import exttable.testselector.VolunteerSelectorMVC;
import options.AppSettings;
import utils.ELocale;
import utils.Localisation;
import utils.LoggerHandler;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.logging.Level;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: Jan 29, 2010
 * Time: 11:59:18 AM
 * To change this template use File | Settings | File Templates.
 */
public class StartPanel {
    private static final int LOCATION = 300;
    public JFrame frame;
    private JPanel enterPanel;
    private JPanel langPanel;

    private JLabel lableName;
    private JLabel labelPass;
    private JLabel titlePanel;
    private JTextField textName;
    private JPasswordField password;
    private JTextField serverAddress;
    private JLabel labelModeOfOperation;
    private JPanel panelModeOfOperation;
    private ButtonGroup buttonGroup;
    private static JRadioButton rbGeneral;
    private static JRadioButton rbSecondary;
    private JLabel serverName;
    private JButton enterButton;
    private JButton exitButton;
    private LoginButtons ruButton;
    private LoginButtons enButton;
    private LoginButtons kzButton;
    private JSeparator upperSeparator;
    private JSeparator buttomSeparator;

    public static JRadioButton getRbGeneral() {
        return rbGeneral;
    }

    public static JRadioButton getRbSecondary() {
        return rbSecondary;
    }

    public StartPanel() {
        AppSettings.createAppSettings();
        init();
    }

    public void init() {
        frame = new JFrame(Localisation.getMessage("title.login"));
        enterPanel = new JPanel();
        enterPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(Localisation.getMessage("form.enter")));

        langPanel = new JPanel();
        langPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(Localisation.getMessage("form.language")));

        lableName = new JLabel(Localisation.getMessage("form.name"));
        labelPass = new JLabel(Localisation.getMessage("form.pass"));
        titlePanel = new JLabel(Localisation.getMessage("form.startofwork"));
        serverName = new JLabel(Localisation.getMessage("form.serveradress"));
        labelModeOfOperation = new JLabel(Localisation.getMessage("modeOfOperation"));

        textName = new JTextField(15);
        password = new JPasswordField(15);
        serverAddress = new JTextField(15);

        password.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                auth();
            }
        });

        panelModeOfOperation = new JPanel();
        rbGeneral = new JRadioButton(Localisation.getMessage("general"));
        rbGeneral.setSelected(true);
        rbSecondary = new JRadioButton(Localisation.getMessage("secondary"));
        buttonGroup = new ButtonGroup();
        buttonGroup.add(rbGeneral);
        buttonGroup.add(rbSecondary);
        panelModeOfOperation.add(rbGeneral);
        panelModeOfOperation.add(rbSecondary);

        enterButton = new JButton(Localisation.getMessage("form.enter"));
        exitButton = new JButton(Localisation.getMessage("form.exit"));
        ruButton = new LoginButtons("RU", "", ELocale.RU);
        enButton = new LoginButtons("EN", "en", ELocale.EN);
        kzButton = new LoginButtons("KZ", "kz", ELocale.KZ);

        upperSeparator = new JSeparator();
        buttomSeparator = new JSeparator();

        enterButton.registerKeyboardAction(enterButton.getActionForKeyStroke(
                KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false)),
                KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false),
                JComponent.WHEN_FOCUSED);

        enterButton.registerKeyboardAction(enterButton.getActionForKeyStroke(
                KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true)),
                KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true),
                JComponent.WHEN_FOCUSED);

        enterButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                auth();
            }
        });

        exitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(1);
            }
        });

        frame.addWindowFocusListener(new WindowAdapter() {
            public void windowGainedFocus(WindowEvent e) {
                textName.requestFocusInWindow();
            }
        });

        enterPanel.add(lableName);
        enterPanel.add(labelPass);
        enterPanel.add(textName);
        enterPanel.add(password);
        enterPanel.add(labelModeOfOperation);
        enterPanel.add(panelModeOfOperation);
        enterPanel.add(enterButton);
        enterPanel.add(exitButton);
//        enterPanel.add(serverAddress);
//        enterPanel.add(serverName);
        enterPanel.setPreferredSize(new Dimension(400, 200));
        organiseEnterSection();

        langPanel.add(kzButton.getButton());
        langPanel.add(ruButton.getButton());
        langPanel.add(enButton.getButton());
        langPanel.setPreferredSize(new Dimension(100, 200));
        organiseLanguagePanel();

        frame.add(enterPanel);
        frame.add(langPanel);
        organiseLayout();


        frame.setSize(600, 300);
        frame.setVisible(true);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation(LOCATION, LOCATION);

    }

    private void auth() {
        char[] p = password.getPassword();

        SGTTestParametrs.getInstance().setServerAddress(serverAddress.getText());

        if (rbGeneral.isSelected()) {
            DbUtils.GENERAL_DATABASE_NAME = "fs1";
            DbUtils.SECONDARY_DATABASE_NAME = DbUtils.GENERAL_DATABASE_NAME + "_copy";
            DbUtils.ModeOfOperation = Localisation.getMessage("general")+" "+Localisation.getMessage("mode");
        } else {
            DbUtils.SECONDARY_DATABASE_NAME = "fs1";
            DbUtils.GENERAL_DATABASE_NAME = DbUtils.SECONDARY_DATABASE_NAME + "_copy";
            DbUtils.ModeOfOperation = Localisation.getMessage("secondary")+" "+Localisation.getMessage("mode");
        }
        System.out.println("GENERAL: " + DbUtils.GENERAL_DATABASE_NAME);
        System.out.println("SECONDARY: " + DbUtils.SECONDARY_DATABASE_NAME);

        if (PasswordChecker.check(textName.getText(), String.valueOf(p), serverAddress.getText())) {
            try {
                SGTTestParametrs.getInstance().setUserName(textName.getText());
                System.out.println("textName.getText(): " + textName.getText());
                SGTTestParametrs.getInstance().setUserAccessLevel(SGTTestParametrs.getUserAccessLevelByUserName(SGTTestParametrs.getInstance().getUserName()));

                frame.dispose();
//                VolunteerSelectorView.getInstance();
                VolunteerSelectorMVC.getInstance();
                StaticMethods.changeInSystem(1, System.getenv("COMPUTERNAME"), SGTTestParametrs.getInstance().getUserName());
            } catch (Exception ez) {
                JOptionPane.showMessageDialog(null, Localisation.getMessage("error.applicationerror"), Localisation.getMessage("error.title"), JOptionPane.WARNING_MESSAGE);
                LoggerHandler.createLogMessage(Level.WARNING, Localisation.getMessage("error.applicationerror") + textName.getText());
                ez.printStackTrace();
            }

        } else {
            JOptionPane.showMessageDialog(null, Localisation.getMessage("error.checkuserpass"), Localisation.getMessage("error.title"), JOptionPane.WARNING_MESSAGE);
        }
    }

    private void organiseEnterSection() {
        SpringLayout enterSectionLayout = new SpringLayout();
        enterPanel.setLayout(enterSectionLayout);

        enterSectionLayout.putConstraint(SpringLayout.WEST, lableName, 50, SpringLayout.WEST, enterPanel);
        enterSectionLayout.putConstraint(SpringLayout.NORTH, lableName, 10, SpringLayout.WEST, enterPanel);

        enterSectionLayout.putConstraint(SpringLayout.WEST, textName, 75, SpringLayout.WEST, lableName);
        enterSectionLayout.putConstraint(SpringLayout.NORTH, textName, 10, SpringLayout.WEST, enterPanel);

        enterSectionLayout.putConstraint(SpringLayout.WEST, labelPass, 50, SpringLayout.WEST, enterPanel);
        enterSectionLayout.putConstraint(SpringLayout.NORTH, labelPass, 10, SpringLayout.SOUTH, lableName);

        enterSectionLayout.putConstraint(SpringLayout.WEST, password, 75, SpringLayout.WEST, labelPass);
        enterSectionLayout.putConstraint(SpringLayout.NORTH, password, 10, SpringLayout.SOUTH, textName);

        enterSectionLayout.putConstraint(SpringLayout.WEST, serverName, 50, SpringLayout.WEST, enterPanel);
        enterSectionLayout.putConstraint(SpringLayout.NORTH, serverName, 10, SpringLayout.SOUTH, labelPass);

        enterSectionLayout.putConstraint(SpringLayout.WEST, serverAddress, 75, SpringLayout.WEST, serverName);
        enterSectionLayout.putConstraint(SpringLayout.NORTH, serverAddress, 10, SpringLayout.SOUTH, password);

        enterSectionLayout.putConstraint(SpringLayout.WEST, labelModeOfOperation, 50, SpringLayout.WEST, enterPanel);
        enterSectionLayout.putConstraint(SpringLayout.NORTH, labelModeOfOperation, 30, SpringLayout.SOUTH, serverName);

        enterSectionLayout.putConstraint(SpringLayout.WEST, panelModeOfOperation, 100, SpringLayout.WEST, labelModeOfOperation);
        enterSectionLayout.putConstraint(SpringLayout.NORTH, panelModeOfOperation, 10, SpringLayout.SOUTH, serverAddress);

        enterSectionLayout.putConstraint(SpringLayout.WEST, enterButton, 0, SpringLayout.WEST, panelModeOfOperation);
        enterSectionLayout.putConstraint(SpringLayout.NORTH, enterButton, 10, SpringLayout.SOUTH, panelModeOfOperation);

        enterSectionLayout.putConstraint(SpringLayout.WEST, exitButton, 5, SpringLayout.EAST, enterButton);
        enterSectionLayout.putConstraint(SpringLayout.NORTH, exitButton, 10, SpringLayout.SOUTH, panelModeOfOperation);


    }

    private void organiseLanguagePanel() {
        SpringLayout languageSectionLayout = new SpringLayout();
        langPanel.setLayout(languageSectionLayout);

        languageSectionLayout.putConstraint(SpringLayout.WEST, ruButton.getButton(), 20, SpringLayout.WEST, langPanel);
        languageSectionLayout.putConstraint(SpringLayout.NORTH, ruButton.getButton(), 0, SpringLayout.NORTH, langPanel);

        languageSectionLayout.putConstraint(SpringLayout.WEST, kzButton.getButton(), 20, SpringLayout.WEST, langPanel);
        languageSectionLayout.putConstraint(SpringLayout.NORTH, kzButton.getButton(), 10, SpringLayout.SOUTH, ruButton.getButton());

        languageSectionLayout.putConstraint(SpringLayout.WEST, enButton.getButton(), 20, SpringLayout.WEST, langPanel);
        languageSectionLayout.putConstraint(SpringLayout.NORTH, enButton.getButton(), 10, SpringLayout.SOUTH, kzButton.getButton());
    }


    private void organiseLayout() {
        SpringLayout mainLayout = new SpringLayout();
        frame.setLayout(mainLayout);

        mainLayout.putConstraint(SpringLayout.WEST, enterPanel, 5, SpringLayout.WEST, frame);
        mainLayout.putConstraint(SpringLayout.NORTH, enterPanel, 1, SpringLayout.SOUTH, frame);

        mainLayout.putConstraint(SpringLayout.WEST, langPanel, 5, SpringLayout.EAST, enterPanel);
        mainLayout.putConstraint(SpringLayout.NORTH, langPanel, 1, SpringLayout.SOUTH, frame);
    }


    private static StartPanel lp = new StartPanel();

    public static StartPanel getInstance() {
        return lp;
    }

    public static void main(String[] args) throws Exception {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    StartPanel.getInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}